package com.tinem.platform.web.netty.websocket.message;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tinem.platform.module.pojo.enums.message.Message;
import com.tinem.platform.module.starter.jms.consumer.ConsumerService;
import com.tinem.platform.module.starter.jms.consumer.SubscribeListener;
import com.tinem.platform.module.starter.jms.enums.TopicEnum;
import com.tinem.platform.web.netty.websocket.session.Session;
import com.tinem.platform.web.netty.websocket.util.MessageUtil;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className SubscribeCommand
 * @description TODO
 * @site
 * @company
 * @create 2021/12/1 14:24:33
 */
@Service("command_subscribe")
public class SubscribeCommand implements Command {

    @Value("${spring.application.name}")
    protected String name;
    @Value("${spring.profiles.active}")
    protected String active;

    @Resource
    ConsumerService consumerService;

    @Override
    public void call(ChannelHandlerContext ctx, Message message) {
        JSONObject req = message.getReq();
        JSONArray chatRoomArray = req.getJSONArray("chatRoom");
        for (int i = 0; i < chatRoomArray.size(); i++) {
            String chatRoom = chatRoomArray.getString(i);
            String connectionId = consumerService.subscribeTopic(TopicEnum.getChatRoomTopic(active,name,chatRoom), new SubscribeListener<Message>() {
                @Override
                public void call(Message message1) {
                    MessageUtil.sendMessage(ctx, message1);
                }
            });
            Session.addConsumerId(ctx,connectionId);
        }
        MessageUtil.sendMessage(ctx,message);
    }

}
